<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="品牌名称" prop="brandName">
        <el-input
          filterable
          v-model="queryParams.brandName"
          placeholder="品牌名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="岗位城市" prop="jobCity">
        <el-cascader
          filterable
          clearable
          placeholder="岗位城市"
          :props="{
            emitPath: false,
          }"
          :show-all-levels="false"
          v-model="queryParams.jobCity"
          :options="regionData"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="销售城市" prop="salesCity">
        <el-cascader
          filterable
          clearable
          placeholder="销售城市"
          :props="{
            emitPath: false,
          }"
          :show-all-levels="false"
          v-model="queryParams.salesCity"
          :options="regionData"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="职位ID" prop="qdkbId">
        <el-input
          type="number"
          v-model="queryParams.qdkbId"
          placeholder="请输入主键，唯一标识职位"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="职位名" prop="positionName">
        <el-input
          v-model="queryParams.positionName"
          placeholder="请输入职位名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-radio-group
      v-model="statusOrScheduleStatus"
      @change="changeStatusOrScheduleStatus()"
      style="margin-bottom: 10px"
    >
      <el-radio-button label="1">排期</el-radio-button>
      <el-radio-button label="2">未排期</el-radio-button>
      <el-radio-button label="3">抢单历史</el-radio-button>
    </el-radio-group>
    <el-table v-loading="loading" :data="wdqdList">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="公司名称" align="center" width="270">
        <template slot-scope="scope">
          <div class="company" @click="kb(scope.row.orderId)">
            <div class="left">
              <img
                :src="scope.row.picUrl ? baseUrl + scope.row.picUrl : c"
                :width="80"
                :height="80"
                alt="职位图片"
              />
              <div class="pro">
                {{ scope.row.combinedInfo.employmentType }}
              </div>
              <div class="id">{{ scope.row.combinedInfo.id }}</div>
            </div>
            <div class="right">
              <div class="titlename">
                {{ scope.row.combinedInfo.positionName }}
              </div>
              <div class="brand">
                {{ scope.row.combinedInfo.brandName }}
              </div>
              <div>
                <el-tag type="danger" v-if="scope.row.interviewdeadline == 'Y'"
                  >面试已截至</el-tag
                >
              </div>
              <div>
                <el-tag type="info" v-if="scope.row.isFull == 'Y'"
                  >已抢满</el-tag
                >
              </div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="负责人"
        align="center"
        prop="positionResponsiblePerson"
      />
      <el-table-column
        label="联系PM"
        align="center"
        prop="phonenumber"
        width="200"
      />
      <el-table-column label="结算规则" width="500">
        <template slot-scope="scope">
          <div class="rule">
            <template v-for="(item, index) in scope.row.rebateInfoArray">
              <div v-if="item.value" :key="index" class="ellipsis">
                <span>{{ item.label }}：</span>
                <el-tooltip
                  class="item"
                  effect="dark"
                  :content="item.value"
                  placement="top-start"
                >
                  <span class="val">{{ item.value }}</span>
                </el-tooltip>
              </div>
            </template>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="更新时间"
        align="center"
        prop="updateTime"
        width="200"
      />
      <el-table-column
        label="抢单时间"
        align="center"
        prop="createTime"
        width="200"
      />
      <el-table-column label="TL/入驻商管理员" align="center" prop="userName" />
      <el-table-column label="团队" align="center" prop="deptName" />
      <el-table-column label="约面" align="center">
        <template slot-scope="scope">
          {{ scope.row.aboutFaceNum || 0 }}
        </template>
      </el-table-column>
      <el-table-column label="到面" align="center">
        <template slot-scope="scope">
          {{ scope.row.toFaceNum || 0 }}
        </template>
      </el-table-column>
      <el-table-column label="offer" align="center">
        <template slot-scope="scope">
          {{ scope.row.offerNum || 0 }}
        </template>
      </el-table-column>
      <el-table-column label="入职" align="center">
        <template slot-scope="scope">
          {{ scope.row.entryNum || 0 }}
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        fixed="right"
        align="center"
        width="200"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-release"
            v-hasPermi="['system:pq:tladd']"
            v-if="statusOrScheduleStatus != '3'"
            @click="handleAddOrUpdate(scope.row)"
            >职位排期</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleStatusChange(scope.row.orderId)"
            v-if="statusOrScheduleStatus != '3'"
            v-hasPermi="['system:wdqd:edit']"
            >手动释放</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改【请填写功能名称】对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="排期周期" prop="scheduleStartDate">
          <el-date-picker
            v-model="form.startEnd"
            @change="getWeekDays()"
            :format="form.scheduleStartDate + '-' + form.scheduleEndDate"
            value-format="yyyy-MM-dd"
            type="week"
            :picker-options="{ firstDayOfWeek: 1 }"
            placeholder="选择周"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="交付顾问" prop="userIds">
          <el-select
            v-model="form.userIds"
            filterable
            multiple
            :disabled="
              $store.state.user.roleId != 3 && $store.state.user.roleId != 4
            "
            placeholder="请选择"
          >
            <el-option
              v-for="(item, index) in userList"
              :key="index"
              :label="item.userName"
              :value="item.userId"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="submitForm"
          :disabled="
            $store.state.user.roleId != 3 && $store.state.user.roleId != 4
          "
          >确 定</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listWdqd, changeStatus } from "@/api/system/wdqd";
import { listPqtlSchedule, tlScheduleAdd } from "@/api/system/pq";
import { regionData } from "@/utils/address.js"; //
import { cateTab } from "@/utils/data.js"; // 根据实际路径调整
import dayjs from "dayjs";
import c from "@/assets/c.jpg";
export default {
  name: "Wdqd",
  data() {
    return {
      c,
      cateTab,
      baseUrl: process.env.VUE_APP_BASE_API,
      regionData,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      wdqdList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      statusOrScheduleStatus: "1",
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        qdkbId: null,
        brandName: null,
        jobCity: null,
        salesCity: null,
        positionName: null,
        status: "1",
        scheduleStatus: "1",
      },
      // 表单参数
      form: {
        scheduleStartDate: null,
        scheduleEndDate: null,
        startEnd: null,
      },
      userList: [],
      // 表单校验
      rules: {
        scheduleStartDate: [
          { required: true, message: "排期开始数据不能为空", trigger: "blur" },
        ],
        userIds: [
          { required: true, message: "用户组不能为空", trigger: "change" },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    kb(orderId) {
      this.$router.push({
        path: "/system/kb",
        query: { orderId },
      });
    },
    getWeekDays() {
      dayjs.extend(require("dayjs/plugin/isoWeek")); // 引入 weekday 插件（可选，增强周处理）
      dayjs.locale("zh-cn"); // 设置中文语言环境（包含周起始日配置）
      if (this.form.startEnd) {
        const currentDate = dayjs(this.form.startEnd);
        const monday = currentDate.isoWeekday(1); // 获取当前周的周一（1 表示周一，0 表示周日）
        this.form.scheduleStartDate = monday
          .subtract(0, "day")
          .format("YYYY-MM-DD");
        this.form.scheduleEndDate = monday.add(6, "day").format("YYYY-MM-DD");
      } else {
        // 设置周起始日为周一（Day.js 默认周日为一周开始，需调整）
        const currentDate = dayjs();
        const monday = currentDate.isoWeekday(1); // 获取当前周的周一（1 表示周一，0 表示周日）
        this.form.scheduleStartDate = monday.add(0, "day").format("YYYY-MM-DD");
        this.form.scheduleEndDate = monday.add(6, "day").format("YYYY-MM-DD");
        this.form.startEnd = monday.add(1, "day").format("YYYY-MM-DD");
      }
      const { scheduleStartDate, scheduleEndDate, qdkbId, tlId, orderId } =
        this.form;
      const pq = {
        scheduleStartDate,
        scheduleEndDate,
        qdkbId,
        tlId,
        orderId,
      };
      listPqtlSchedule(pq).then((res) => {
        this.form.userIds = res.userIds;
        this.userList = res.users;
      });
    },
    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true;
      listWdqd(this.queryParams).then((response) => {
        this.wdqdList = response.rows;
        this.wdqdList.forEach((row) => {
          row.rebateInfoArray = [
            { label: "返费类别", value: row.rebateType },
            { label: "生效日期", value: row.effectiveDate },
            { label: "返费规则", value: row.rebateRule },
            { label: "价格规则", value: row.priceRule },
            {
              label: "返费周期",
              value:
                row.rebateType != "一次性返费" ? row.refundPeriod + "月" : "",
            },
            {
              label: "返费价格",
              value: row.rebatePrice + cateTab[row.rebateType],
            },
            { label: "返费条件", value: row.rebateCondition },

            { label: "首次返费最低考勤要求", value: row.firstRefund },
            { label: "返费说明", value: row.refundExplanation },
          ];
        });
        this.wdqdList.forEach((row) => {
          row.combinedInfo = {
            id: `ID:${row.qdkbId}`,
            employmentType: row.employmentType,
            positionName: row.positionName,
            brandName: row.brandName,
          };
        });
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          const { scheduleStartDate, scheduleEndDate, orderId, qdkbId, tlId } =
            this.form;
          const userIdsString = this.form.userIds.join("_");
          tlScheduleAdd({
            scheduleStartDate,
            scheduleEndDate,
            tlId,
            userIdsString,
            orderId,
            qdkbId,
          }).then((response) => {
            this.$modal.msgSuccess("成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },
    // 表单重置
    reset() {
      this.form = {
        orderId: null,
        qdkbId: null,
        userIds: null,
        scheduleStartDate: null,
        scheduleEndDate: null,
        startEnd: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    handleAddOrUpdate(row) {
      this.reset();
      this.form.qdkbId = row.qdkbId;
      this.form.tlId = row.userId;
      this.form.orderId = row.orderId;
      this.getWeekDays();
      this.open = true;
    },

    changeStatusOrScheduleStatus() {
      if (this.statusOrScheduleStatus == "3") {
        this.queryParams.status = "";
        this.queryParams.scheduleStatus = "";
      } else {
        this.queryParams.status = "1";
        this.queryParams.scheduleStatus = this.statusOrScheduleStatus;
      }
      this.handleQuery();
    },

    handleStatusChange(orderId) {
      this.$modal
        .confirm("释放职位不影响已排期的数据记录。确定要释放么？")
        .then(function () {
          return changeStatus(orderId);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("释放成功");
        })
        .catch(() => {});
    },
  },
};
</script>
